﻿using com.fmtx.Model;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using com.fmtx.IDal;
using fmtx.Framework.DALFactory;
using fmtx.Framework.Model;
using System.Text;
using System.Configuration;
using fmtx.Framework.Web;
using fmtx.Framework.Img;
using fmtx.Framework.OpenOAuth;

namespace website.Areas.Write.Controllers
{
    public class ArticleController : RegBaseController
    {
        //
        // GET: /Write/Article/
        private IArticle obj = DataAccess<IArticle>.GetObject();
        private IArticleType type = DataAccess<IArticleType>.GetObject();
        private ICity city = DataAccess<ICity>.GetObject();
        private IPlace place = DataAccess<IPlace>.GetObject();
        private IKeyWord keyword = DataAccess<IKeyWord>.GetObject();
        private IOAuthUser _oauth = DataAccess<IOAuthUser>.GetObject();

        /// <summary>
        /// 显示编辑
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public ActionResult Edit(int? id)
        {
            Article model = null;
            ViewBag.typelist = type.Query(userInfo.Uid);
            if (id != null)
            {
                model = obj.Get(id.Value);
            }
            else {
                model = new Article();
                var tempdata = TempData["collecttxt"]+"";
                if (!string.IsNullOrEmpty(tempdata))
                {
                    model.Content = tempdata;
                }
            }
            ViewBag.Keyword = keyword.QueryHost(10,Target.ARTICLE);
            return View(model);
        }

        /// <summary>
        /// 编辑文章
        /// </summary>
        /// <param name="model"></param>
        /// <returns></returns>
        [HttpPost]
        [ValidateInput(false)]
        public ActionResult Edit(Article model)
        {
            if (ModelState.IsValid)
            {
                bool istrue = false;
                string firstimg=model.FrontCover;
                model.Content = StaticCs.SaveHtmlWord(model.Content, ref firstimg);
                model.Summary = model.Content.RemoveHtml(200);
                if (!string.IsNullOrEmpty(firstimg))
                {
                    model.FrontCover = firstimg;
                    model.Scale = ImageFactory.GetScale(Server.MapPath(StaticCs.VirtualPath + firstimg));
                }
                model.IsView = true;
                if (userInfo.IsSystem)
                {
                    model.Statu = Approved.IsPass;
                }
                else {
                    model.Statu = Approved.Verifying;
                }
                model.Uid = userInfo.Uid;
                List<AreaKey> areas = model.Content.FindArea();
                if (areas != null && areas.Count>0)
                {
                    var item = areas.OrderBy(o => o.Type).FirstOrDefault();
                    model.Address = item.Name;
                    model.AddressUrl = item.Url;
                    model.AreaKeys = areas;
                }
                if (string.IsNullOrEmpty(model.KeyWord))
                {
                    model.KeyWord = StaticCs.SaveKeyWord(model.Content.RemoveHtml());
                }
                if (model.Id == 0)
                {
                    model.InTime = DateTime.Now;
                    model.KeyWord=StaticCs.SaveKeyWord(model.KeyWord,Target.ARTICLE);
                    istrue = obj.Add(model);
                    if (userInfo.IsSystem)
                    {
                        ArticleCache.Insert(model);
                    }
                    else {
                        var oauths = _oauth.Query(userInfo.Uid);
                        if (oauths != null)
                        {
                            foreach (var item in oauths)
                            {
                                switch (item.Type)
                                {
                                    case OAuthType.QQ:
                                        if (!string.IsNullOrEmpty(model.FrontCover))
                                        {
                                            shareQQweibo(model.Title, Server.MapPath(StaticCs.VirtualPath + model.FrontCover), item.AccessToken, item.OpenId, model.Id);
                                        }
                                        else
                                        {
                                            shareQQweiboTxt(model.Title, item.AccessToken, item.OpenId, model.Id);
                                            //shareQQ(model.Title, item.AccessToken, item.OpenId, model.Id);
                                        }
                                        break;
                                    case OAuthType.Weibo:
                                        shareSinaTxt(model.Title, item.AccessToken, model.Id);
                                        break;
                                    case OAuthType.TxWeibo:
                                        break;
                                    default:
                                        break;
                                }
                            }
                        }
                    }
                }
                else
                {
                    var oldmodel = obj.Get(model.Id);
                    oldmodel.Title = model.Title;
                    oldmodel.FrontCover = model.FrontCover;
                    oldmodel.TypeId = model.TypeId;
                    oldmodel.KeyWord = StaticCs.SaveKeyWord(model.KeyWord, Target.ARTICLE);
                    oldmodel.PlaceTag = model.PlaceTag;
                    oldmodel.Statu = model.Statu;
                    istrue = obj.Update(oldmodel);
                    if (userInfo.IsSystem)
                    {
                        ArticleCache.Update(oldmodel);
                    }
                }

                if (istrue)
                {
                    StaticCs.RemoveUserFolder(userInfo.Uid);
                    return Redirect("/article/" + model.Id);
                }
            }
            ViewBag.typelist = type.Query(userInfo.Uid);
            ViewBag.Keyword = keyword.QueryHost(10,Target.ARTICLE);
            return View(model);
        }

        private void shareQQ(string title,string access_token,string openid,int aid)
        {
            QQShera shera=new QQShera();
            shera.Title = title;
            shera.Url = "http://lvyougl.com/article/"+aid;
            shera.Site = "旅游攻略";
            shera.Fromurl = "http://lvyougl.com";
            var msg = QQOAuth.ShareQQ(shera, ConfigurationManager.AppSettings["qq_appKey"], access_token, openid);
        }

        private void shareQQweibo(string title,string file, string access_token, string openid, int aid)
        {
            QQShera shera = new QQShera();
            shera.Body = title;
            shera.Url = "http://lvyougl.com/article/" + aid;
            shera.Site = "旅游攻略";
            shera.File = file;
            var msg = QQOAuth.ShareQQWeiboTxtPic(shera, ConfigurationManager.AppSettings["qq_appKey"], access_token, openid);
        }

        private void shareQQweiboTxt(string title, string access_token, string openid, int aid)
        {
            QQShera shera = new QQShera();
            shera.Body = title;
            shera.Url = "http://lvyougl.com/article/" + aid;
            shera.Site = "旅游攻略";
            var msg = QQOAuth.ShareQQTxt(shera, ConfigurationManager.AppSettings["qq_appKey"], access_token, openid);
        }

        private void shareSinaTxt(string title, string access_token, int aid)
        {
            SinaShera shera=new SinaShera();
            shera.Body = title + " http://lvyougl.com/article/" + aid;
            SinaOAuth.ShareSinaTxt(shera, access_token);
        }


        /// <summary>
        /// 编辑文章
        /// </summary>
        /// <param name="model"></param>
        /// <returns></returns>
        [ValidateInput(false)]
        public ActionResult AppInsert(Article model)
        {
            model.Source = HttpUtility.UrlDecode(model.Source);
            if (obj.HasSource(model.Source))
            {
                Response.Write("");
                Response.End();
                return null;
            }
            bool istrue = false;
            IUserInfo user = DataAccess<IUserInfo>.GetObject();
            var ubean = user.Get(model.Uid);
            LoginModel.SetUserInfo(ubean);
            string firstimg = model.FrontCover;
            model.Content = StaticCs.SaveHtmlWord(HttpUtility.UrlDecode(model.Content), ref firstimg);
            model.Content = WebHelper.Replace(model.Content, "<a(.*?)>", "");
            model.Content = WebHelper.Replace(model.Content, @"</[\s\t\r\n]*a[\s\t\r\n]*>", "");
            model.Summary = model.Content.RemoveHtml(200);
            if (!string.IsNullOrEmpty(firstimg))
            {
                model.FrontCover = firstimg;
                model.Scale = ImageFactory.GetScale(Server.MapPath(StaticCs.VirtualPath + firstimg));
            }
            model.IsView = true;
            model.InTime = DateTime.Now;
            model.Statu = Approved.IsPass;
            List<AreaKey> areas = model.Content.FindArea();
            if (areas != null)
            {
                var item = areas.OrderBy(o=>o.Type).FirstOrDefault();
                model.Address = item.Name;
                model.AddressUrl = item.Url;
                model.AreaKeys = areas;
            }

            model.KeyWord = StaticCs.SaveKeyWord(model.Content.RemoveHtml());
            model.KeyWord = StaticCs.SaveKeyWord(model.KeyWord, Target.ARTICLE);
            istrue = obj.Add(model);

            if (istrue)
            {
                ArticleCache.Insert(model);
                //StaticCs.RemoveUserFolder(userInfo.Uid);
                Response.Write(model.Id);
                Response.End();
                return null;
            }
            Response.Write("") ;
            Response.End();
            return null;
        }

    }
}
